// Copyright Epic Games, Inc. All Rights Reserved.


#include "Subsystem/FlowWorldSubsystem.h"
#include "Asset/CustomizeFlowAsset.h"
#include "Engine/World.h"

#if WITH_EDITOR
#include "Kismet2/KismetEditorUtilities.h"
#include "Actor/CustomizeFlowEmptyActor.h"
#endif
#include "Kismet/GameplayStatics.h"
#include "EngineUtils.h"


#if WITH_EDITOR
class UCustomizeFlowAsset* UFlowWorldSubsystem::GetCurrentLevelCusFlowAssetObj(bool bDontCreate)
{
	UWorld* World = GetWorld();
	ACusFEmptyActor* FlowEmptyActor = nullptr;
	
	for (auto& TmpActor : World->GetCurrentLevel()->Actors)
	{
		if (TmpActor && TmpActor->IsA<ACusFEmptyActor>())
		{
			FlowEmptyActor = Cast<ACusFEmptyActor>(TmpActor);
			break;
		}
	}

	if (FlowEmptyActor == nullptr)
	{
		FActorSpawnParameters SpawnInfo;
		SpawnInfo.OverrideLevel = World->GetCurrentLevel();
		SpawnInfo.ObjectFlags = RF_Transactional;
		FlowEmptyActor = World->SpawnActor<ACusFEmptyActor>(ACusFEmptyActor::StaticClass(), SpawnInfo);
	}

	UCustomizeFlowAsset* CustomizeFlowAssetObj = nullptr;
	CustomizeFlowAssetObj = FlowEmptyActor->GetCustomizeFlowAssetObj();
	if (!CustomizeFlowAssetObj)
	{
		const FString FlowSystemName = GetWorld()->GetCurrentLevel()->GetName() + "Flow";

		if (UObject* ExistingObject = StaticFindObject(nullptr, World, *FlowSystemName))
		{
			ExistingObject->Rename(nullptr, nullptr, REN_DoNotDirty | REN_DontCreateRedirectors | REN_ForceNoResetLoaders | REN_NonTransactional);
		}
		CustomizeFlowAssetObj = NewObject<UCustomizeFlowAsset>(GetWorld()->GetCurrentLevel(), UCustomizeFlowAsset::StaticClass(), FName(*FlowSystemName), RF_Public);
		FlowEmptyActor->SetCustomizeFlowAssetObj(CustomizeFlowAssetObj);
		CustomizeFlowAssetObj->ClearFlags(RF_Standalone);
	}
	return CustomizeFlowAssetObj;
}

#endif

